/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package exclusionmutua;

import java.util.Iterator;
import java.util.Map;
import java.util.Queue;
import jxta.CrearInputPipe;
import net.jxta.endpoint.Message;
import net.jxta.pipe.PipeMsgEvent;
import net.jxta.pipe.PipeMsgListener;
import net.jxta.protocol.PipeAdvertisement;
import utilidades.AdminMensaje;

/**
 *
 * @author Eduardo
 */
public class InputPipeTokenEM implements PipeMsgListener{
    private Map<String,ExclusionMutua> exclusionMutuaMap;
    private final TokenListener tokenListener;
    private static Token tokenViejo;

    public InputPipeTokenEM(Map<String, ExclusionMutua> exclusionMutuaMap,
            TokenListener tokenListener) {
        this.exclusionMutuaMap = exclusionMutuaMap;
        this.tokenListener = tokenListener;
    }

    public void pipeMsgEvent(PipeMsgEvent event) {

        Message msg;
        try {
            // Obtain the message from the event


            msg = event.getMessage();
            if (msg == null) {
                System.err.println("Received an empty message");
                return;
            }

             Token tokenNuevo = AdminMensaje.getTokenFromEnvioToken(msg, AdminMensaje.NAME_SPACE);
             System.out.println("========COMPROBANDO SI LLEGA DOS TOKENS IGUALES.================");
             if(tokenNuevo.equals(tokenViejo)){
                 System.out.println("========Descartando token repetido.================");
                 return;
            }
            tokenViejo = tokenNuevo;
             String idDocumento = tokenNuevo.getIdDocumento();
//            for(PipeAdvertisement pipe :  tokenNuevo.getLNPeerIDs()){
//                Integer seqNumb = tokenNuevo.getLNSquenceNumber(pipe);
//            }
//            Queue q = tokenNuevo.getCola();
//            for(Iterator<PipeAdvertisement> it = q.iterator(); it.hasNext();){
//                PipeAdvertisement pipe = it.next();
//            }
             ExclusionMutua em = exclusionMutuaMap.get(idDocumento);
             //Actualiza la vista.
             System.out.println("====================EXCLUSIÓN MUTUA=======================");
             System.out.println("===================GESTIONANDO TOKEN======================");
             System.out.println("Se recibio el token asociado al documento [id:" + idDocumento + "]");
             tokenListener.gestionarToken(tokenNuevo);
             em.receiveToken(tokenNuevo);
            // dump the message content to screen
            CrearInputPipe.printMessageStats(msg, true);
        } catch (Exception e) {
            System.err.println("Error leyendo el mensaje de petición de Sección Critica");
            e.printStackTrace();
            return;
        }

//        // get all the message elements
//        Message.ElementIterator en = msg.getMessageElements();
//
//        if (!en.hasNext()) {
//            return;
//        }

//        // get the message element in the name space PipeClient.MESSAGE_NAME_SPACE
//        MessageElement msgElement = msg.getMessageElement(null, "PipeClient.MESSAGE_NAME_SPACE");
//
//        // Get message
//        if (msgElement.toString() == null) {
//            System.out.println("null msg received");
//        } else {
//            Date date = new Date(System.currentTimeMillis());
//            System.out.println("Message received at :" + date.toString());
//            System.out.println("Message  created at :" + msgElement.toString());
//        }
    }

}
